package com.yangjun.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class DvDateUtils {
	public static final String Format_Date = "yyyy-MM-dd";
	public static final String Format_Time = "HH:mm:ss";
	public static final String Format_DateTime = "yyyy-MM-dd HH:mm:ss";
	public static final String FORMAT_DATE_TIME = "yyyy-MM-dd-HH-mm-ss"; 

	public static Integer ONEDAY_MS = 24*60*60*1000;
	public static String getCurrentDate(Date date) {
		return new SimpleDateFormat("yyyy-MM-dd").format(date);
	}
	/** 
     * 将日期字符串转化为日期。失败返回null。 
     * @param date 日期字符串 
     * @param parttern 日期格式 
     * @return 日期 
     */  
    public static Date StringToDate(String date, String parttern) {  
        Date myDate = null;  
        if (date != null) {  
            try {  
                myDate = getDateFormat(parttern).parse(date);  
            } catch (Exception e) {  
            }  
        }  
        return myDate;  
    }  
    
    /** 
     * 获取SimpleDateFormat 
     * @param parttern 日期格式 
     * @return SimpleDateFormat对象 
     * @throws RuntimeException 异常：非法日期格式 
     */  
    private static SimpleDateFormat getDateFormat(String parttern) throws RuntimeException {  
        return new SimpleDateFormat(parttern);  
    }  
	
	public static String getYesterDayOfLastYear() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.YEAR, -1);
		return DvDateUtils.format(calendar.getTime(), "yyyy-MM-dd");
	}
	/**
	 * 前一天时间 时间格式是(yyyy-MM-dd)
	 * 
	 * @return string
	 */
	public static String getDate(Date date,int index) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH,index);
		date = calendar.getTime();
		return new SimpleDateFormat("yyyy-MM-dd").format(date);
	}
	
	  /**  
     * 计算两个日期之间相差的天数  (左开右闭)
     * @param beginDate 较小的时间 
     * @param endDate  较大的时间 
     * @return 相差天数 
     * @throws ParseException  
     */    
    public static int daysBetween(Date endDate,Date beginDate) throws ParseException    
    {    
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        endDate=sdf.parse(sdf.format(endDate));  
        beginDate=sdf.parse(sdf.format(beginDate));  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(beginDate);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(endDate);    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));           
    }    
      
	/** 
	*字符串的日期格式的计算  (左开右闭)
	*/  
    public static int daysBetween(String endDate,String beginDate) throws ParseException{  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(sdf.parse(beginDate));    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(sdf.parse(endDate));    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));     
    }  
	  /**
     * 小时偏移量
     * @param ts
     * @param offset
     * @return
     */
    public static Date getOffsetHour(Date ts,int offset) {
        if (ts == null) return null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(ts);
        calendar.add(Calendar.HOUR, offset);
        return calendar.getTime();
    }
    
    
    /**
     * 日期格式化
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        if (date == null) return "";
        DateFormat formt = new SimpleDateFormat(pattern);
        return formt.format(date);
    }
    
    /**
    * 字符串转换成日期
    * @param str
    * @return date
    */
    public static Date StrToDate(String str,String pattern) {
      
       SimpleDateFormat format = new SimpleDateFormat(pattern);
       Date date = null;
       try {
        date = format.parse(str);
       } catch (ParseException e) {
        e.printStackTrace();
       }
       return date;
    }

    
    /**
     * eg ： 输入（2013-09-18 16:05:44，-1 ）得到2013-08-18 16:05:44.
     *
     * @param date
     * @param offset
     * @return DateUtils
     * @Title: getOffsetDayStart
     */
    public static Date getOffsetMonth(Date date, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, offset);
        return calendar.getTime();
    }
    
    /**
     * eg ： 输入（2013-09-18 16:05:44 ，-1 ）得到2013-09-17 16:05:44
     *
     * @param date
     * @param offset
     * @return DateUtils
     * @Title: getOffsetDayStart
     */
    public static Date getOffsetDay(Date date, long offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        long time = calendar.getTimeInMillis() + offset * ONEDAY_MS;

        return new Date(time);
    }
	/**
	 * 根据开始时间和结束时间返回时间段内的时间集合
	 * @param beginDate
	 * @param endDate
	 * @return List
	 */
	public static List<String> getDatesBetweenTwoDate(Date beginDate, Date endDate, String pattern) {    
//		System.out.println(format(beginDate,pattern));
//		System.out.println(format(endDate,pattern));
		
	    List<String> lDate = new ArrayList<String>();
	    lDate.add(format(beginDate,pattern));//把开始时间加入集合
	    Calendar cal = Calendar.getInstance();
	    //使用给定的 Date 设置此 Calendar 的时间
	    cal.setTime(beginDate);
	    boolean bContinue = true;
	    while (bContinue) {
	        //根据日历的规则，为给定的日历字段添加或减去指定的时间量
	        cal.add(Calendar.DAY_OF_MONTH, 1);
	        // 测试此日期是否在指定日期之后
	        if (endDate.after(cal.getTime())) {
	            lDate.add(format(cal.getTime(),pattern));
	        } else {
	            break;
	        }
	    }
	    lDate.add(format(endDate,pattern));//把结束时间加入集合
	    return lDate;
	}
	
	 /**
     * 得到某年某周的第一天
     *
     * @param year
     * @param week
     * @return
     */
    public static Date getFirstDayOfWeek(int year, int week) {
        week = week - 1;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DATE, 1);

        Calendar cal = (Calendar) calendar.clone();
        cal.add(Calendar.DATE, week * 7);

        return getFirstDayOfWeek(cal.getTime());
    }

    /**
     * 得到某年某周的最后一天
     *
     * @param year
     * @param week
     * @return
     */
    public static Date getLastDayOfWeek(int year, int week) {
        week = week - 1;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DATE, 1);
        Calendar cal = (Calendar) calendar.clone();
        cal.add(Calendar.DATE, week * 7);

        return getLastDayOfWeek(cal.getTime());
    }

	
	  /**
     * 取得当前日期所在周的第一天
     *
     * @param date
     * @return
     */
    public static Date getFirstDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_WEEK,
                      calendar.getFirstDayOfWeek()); 
        
//        System.out.println("当前周="+calendar.get(Calendar.WEEK_OF_YEAR));
        return calendar.getTime();
    }

    /**
     * 取得当前日期所在周的最后一天
     *
     * @param date
     * @return
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_WEEK,
                     calendar.getFirstDayOfWeek() + 6); 
        return calendar.getTime();
    }

    /**
     * 取得当前日期所在周的前一周最后一天
     *
     * @param date
     * @return
     */
    public static Date getLastDayOfLastWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return getLastDayOfWeek(calendar.get(Calendar.YEAR),
                                calendar.get(Calendar.WEEK_OF_YEAR) - 1);
    }
    /**
     * 取得当前日期所在周的前一周第一天
     * @param date
     * @return
     */
    public static Date getFirstDayOfLastWeek(Date date) {
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(date);
    	return getFirstDayOfWeek(calendar.get(Calendar.YEAR),
    			calendar.get(Calendar.WEEK_OF_YEAR) - 1) ;
    }

	
    /**
     * 返回指定日期的月的第一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getFirstDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR),
                     calendar.get(Calendar.MONTH), 1);
        return calendar.getTime();
    }

    /**
     * 返回指定年月的月的第一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getFirstDayOfMonth(Integer year, Integer month) {
        Calendar calendar = Calendar.getInstance();
        if (year == null) {
            year = calendar.get(Calendar.YEAR);
        }
        if (month == null) {
            month = calendar.get(Calendar.MONTH);
        }
        calendar.set(year, month, 1);
        return calendar.getTime();
    }

    /**
     * 返回指定日期的月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR),
                     calendar.get(Calendar.MONTH), 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTime();
    }

    /**
     * 返回指定年月的月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfMonth(Integer year, Integer month) {
        Calendar calendar = Calendar.getInstance();
        if (year == null) {
            year = calendar.get(Calendar.YEAR);
        }
        if (month == null) {
            month = calendar.get(Calendar.MONTH);
        }
        calendar.set(year, month, 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTime();
    }

    /**
     * 返回指定日期的上个月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfLastMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR),
                     calendar.get(Calendar.MONTH) - 1, 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTime();
    }
	 public static int getWeekOfYear(Date date) {
		  Calendar c = new GregorianCalendar();
		  c.setFirstDayOfWeek(Calendar.MONDAY);
		  c.setMinimalDaysInFirstWeek(7);
		  c.setTime(date);
		  return c.get(Calendar.WEEK_OF_YEAR);
		 }
    public static int  getYear(Date date){
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(date);
    	return calendar.get(Calendar.YEAR);
    }
    public static int  getMonth(Date date){
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(date);
    	return calendar.get(Calendar.MONTH);
    }
    
    
//	public static void main(String[] args) {
//		System.out.println("当前周的第一天=="+format(getFirstDayOfWeek(new Date()),"yyyy-MM-dd"));
//		System.out.println("当前周的最后一天=="+format(getLastDayOfWeek(new Date()),"yyyy-MM-dd"));
//		System.out.println("上周的第一天=="+format(getOffsetDay(getFirstDayOfWeek(new Date()),-7),"yyyy-MM-dd"));
//		System.out.println("上周的最后一天=="+format(getOffsetDay(getLastDayOfWeek(new Date()),-7),"yyyy-MM-dd"));
//		System.out.println("当月的第一天=="+format(getFirstDayOfMonth(new Date()),"yyyy-MM-dd"));
//		System.out.println("当月的最后一天=="+format(getLastDayOfMonth(new Date()),"yyyy-MM-dd"));
//		System.out.println("上月的第一天=="+format(getFirstDayOfMonth(getLastDayOfLastMonth(new Date())),"yyyy-MM-dd"));
//		System.out.println("上月的最后一天=="+format(getLastDayOfLastMonth(new Date()),"yyyy-MM-dd"));
//		
//		Date offsetDaystart = getOffsetDay(new Date(),-30);
//		Date offsetDayend = getOffsetDay(new Date(),-1);
//		System.out.println(getDatesBetweenTwoDate(offsetDaystart,offsetDayend,"MM-dd"));
//	}
}
